package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.dtos.PageResponseResult;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustomException;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.dto.WmNewsDto;
import com.heima.wemedia.dto.WmNewsPageReqDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.pojo.WmNews;
import com.heima.wemedia.pojo.WmNewsMaterial;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.utils.WmThreadLocalUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 查询自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<List<WmNews>> findAll(WmNewsPageReqDto dto) {
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //获取当前登录人的信息
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //2.分页条件查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQuery = Wrappers.<WmNews>lambdaQuery();

        if (ObjectUtil.isNotEmpty(dto.getKeyword())) {
            lambdaQuery.like(WmNews::getTitle, dto.getKeyword());
        }

        if (ObjectUtil.isNotEmpty(dto.getStatus())) {
            lambdaQuery.eq(WmNews::getStatus, dto.getStatus());
        }

        if (ObjectUtil.isNotEmpty(dto.getChannelId())) {
            lambdaQuery.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (ObjectUtil.isAllNotEmpty(dto.getBeginPubDate(), dto.getEndPubDate())) {
            lambdaQuery.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        lambdaQuery.eq(WmNews::getUserId, user.getId())
                .orderByDesc(WmNews::getCreatedTime);

        super.page(page, lambdaQuery);

        return PageResponseResult.<List<WmNews>>builder()
                .size(dto.getSize())
                .currentPage(dto.getPage())
                .data(page.getRecords())
                .total(Convert.toInt(page.getTotal()))
                .build();

    }

    /**
     * 文章发布
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Object> submitNews(WmNewsDto dto) {
        if (ObjectUtil.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        WmNews wmNews = BeanUtil.copyProperties(dto, WmNews.class);
        if (CollUtil.isNotEmpty(dto.getImages())) {
            String strImages = StrUtil.join(",", dto.getImages());
            wmNews.setImages(strImages);
        }

        if (ObjectUtil.equals(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }

        if (ObjectUtil.isEmpty(wmNews.getId())) {
            wmNews.setUserId(user.getId());
            wmNews.setPublishTime(new Date());
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable(Convert.toShort(1));
            super.save(wmNews);
        }

        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, wmNews.getId());
        this.wmNewsMaterialMapper.delete(queryWrapper);
        super.updateById(wmNews);


        //2.判断是否为草稿  如果为草稿结束当前方法
        if (ObjectUtil.equals(dto.getStatus(), WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<JSONObject> jsonObjects = JSONUtil.toList(dto.getContent(), JSONObject.class);
        List<String> imageList = StreamUtil.of(jsonObjects)
                .filter(entries -> StrUtil.equals(entries.getStr("type"), "images"))
                .map(entries -> entries.getStr("value"))
                .collect(Collectors.toList());

        saveRelativeInfoForContent(imageList, wmNews.getId());

        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto, wmNews, imageList);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public WmNews checkDetail(Integer id) {
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getId, id);
        return this.getOne(queryWrapper);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNew(Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            return ResponseResult.errorResult(501, "文章Id不可缺少");
        }
        WmNews wmNews = this.getById(id);
        if (ObjectUtil.isEmpty(wmNews)) {
            return ResponseResult.errorResult(1002, "文章不存在");
        }
        boolean result = this.removeById(id);
        if (result) {
            return ResponseResult.okResult(200, "操作成功");
        }

        return ResponseResult.errorResult(501, "文章已发布，不能删除");
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(WmNewsDto dto) {

        return null;
    }


    /**
     * 处理文章内容图片与素材的关系
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材的关系到数据库中
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if (CollUtil.isEmpty(materials)) {
            return;
        }
        //通过图片的url查询素材的id
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

        //判断素材是否有效
        if (CollUtil.isEmpty(dbMaterials)) {
            //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        if (materials.size() != dbMaterials.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        List<Integer> idList = CollStreamUtil.toList(dbMaterials, WmMaterial::getId);

        //批量保存
        wmNewsMaterialMapper.saveRelations(idList, newsId, type);
    }


    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     * <p>
     * 第二个功能：保存封面图片与素材的关系
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
        List<String> images = dto.getImages();
        //如果当前封面类型为自动，则设置封面类型的数据
        if (ObjectUtil.equal(dto.getType(), WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (CollUtil.isEmpty(materials)) {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (CollUtil.size(materials) >= 3) {
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = CollUtil.sub(materials, 0, 3);
            } else {
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = CollUtil.sub(materials, 0, 1);
            }

            //修改文章
            if (CollUtil.isNotEmpty(images)) {
                wmNews.setImages(StrUtil.join(",", images));
            }
            super.updateById(wmNews);
        }
        if (CollUtil.isNotEmpty(images)) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }
}








































